
/*
 * 公共方法,建议涉及到一些公用方法可以再里面扩展
 */

//防止ie8报错
window.console = window.console || (function () {
        var c = {};
        c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile = c.clear = c.exception = c.trace = c.assert = function () {
        };
        return c;
    })();
//公共方法
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node, CommonJS之类的
        module.exports = factory(require('jquery'));
    } else {
        // 浏览器全局变量(root 即 window)
        var obj = factory(jQuery);
        root.Pub = obj;
    }
})(this, function ($) {
    var Pub = {
        debug: true, //开启调试开关
        server: 'https://coupon.bravets.com', //服务器接口域名-测试
        // server: 'https://app.yicheezu.com', //服务器接口域名-正式
        imgHost: 'http://img.bravets.com',
        token: 'coupon357932',
        platfrom: 'wx',
        clientRoot: '', //前端代码根路径-测试
        // clientRoot: '/fupin/', //前端代码根路径-正式
        /**
         * 对jquery的post进一步封装，默认会注入_app\_platform\_passport,
         * 同时对返回数据默认进行通用错误处理,未登录会进行登录处理
         * @param {string} url 请求地址
         * @param {object} data 请求附加参数
         * @param {function} callback 异步回调函数,默认已对数据进行通用错误处理
         * @param {string} type 返回内容类型
         *
         * @returns {object}  返回Deferred对象，支持promise
         */
        post: function (url, data, callback, type) {
            if(url.indexOf('http') === - 1){
                return this._ajax(this.server + url, data, callback, type);
              }else{
                return this._ajax(url, data, callback, type);
            }
        },
        /**
         * 对jquery的post进一步封装，默认会注入_app\_platform\_passport,
         * 同时对返回数据默认进行通用错误处理,未登录会进行登录处理
         * @param {string} url 请求地址
         * @param {object} data 请求附加参数
         * @param {function} callback 异步回调函数,默认已对数据进行通用错误处理
         * @param {string} type 返回内容类型
         *
         * @returns {object}  返回Deferred对象，支持promise
         */
        get: function (url, data, callback, type) {
            if(url.indexOf('http') === -1){
                return this._ajax(this.server + url, data, callback, type, "get");
            }else{
                return this._ajax(url, data, callback, type, "get");
            }
        },
        /**
         * 私有方法不要调用
         */
        _ajax: function (url, data, callback, type, method) {
            var self = this,
                filterCallback;
            if ($.isFunction(data)) {
                type = type || callback;
                callback = data;
                data = undefined;
            }

            url = this.getAbsoluteUrl(url);

            if (url.indexOf("_passport") === -1 && ($.isPlainObject(data) && !data.entriedCode)) {
                data = $.extend(this.getAuthInfo(), data);
            } else if (url.indexOf("_passport") === -1 && data === undefined) {
                data = this.getAuthInfo();
            }

            //回调函数注入处理,通用错误处理
            if ($.isFunction(callback)) {
                filterCallback = function (data, textStatus, jqXHR) {
                    data = self.catchCommonError(data);
                    callback(data, textStatus, jqXHR);
                };
            }

            var deferred = new $.Deferred();

            var xhr = method === "get" ? $.get(url, data, filterCallback, type) : $.post(url, data, filterCallback, type);

            xhr.then(
                function (data, textStatus, jqXHR) { //成功回调
                    data = self.catchCommonError(data);
                    deferred.resolveWith(this, [data, textStatus, jqXHR]);

                },
                function (XMLHttpRequest, textStatus, errorThrown) { //失败回调
                    deferred.rejectWith(this, [XMLHttpRequest, textStatus, errorThrown]);
                }
            );

            var promise = deferred.promise();

            promise.abort = function () {
                xhr.abort();
                deferred.reject("abort");
            };

            return promise;
        },
        /**
         * 签名标识
         * obj是数组[]
         */
        sign: function(data){
            var keys = [], arrs = [];
            for(var i in data){
                if(data.hasOwnProperty(i)){
                    keys.push(i);
                }
            }
            arrs = keys.sort();
            var result = '';
            for(var j=0; j<arrs.length; j++){
                var l = arrs[j];
                result += data[l] + '&';
            }
            var firstStr = result.charAt(0);
            if(firstStr === '&'){
               result = result.substring(1,result.length);
            }
            var r = result + Pub.token;
            return md5(r);

        },
        /**
         * 浏览器判断是否是
         */
        browser:{
            isAndroid : navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1, //android终端
            isiOS : !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            isWeChat: window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger'
        },
        /**
         *搜索ID或名字等，通过关键词获取的
         */
        searchToObject: function () {
            var pairs = window.location.search.substring(1).split("&"),
                obj = {},
                i;
            for (i in pairs) {
                if (pairs[i] === "")
                    continue;

                pair = pairs[i].split("=");
                obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
            }
            return obj;
        },
        /**
         *倒计时方法
         */
        countDown: function (time, id) {
            var dayElem = $(id).find('.day');
            var hourElem = $(id).find('.hour');
            var minuteElem = $(id).find('.minute');
            var secondElem = $(id).find('.second');
            var endTime = new Date(time).getTime(),
                sysSecond = (endTime - new Date().getTime()) / 1000;
            var timer = setInterval(function () {
                if (sysSecond > 1) {
                    sysSecond -= 1;
                    var day = Math.floor((sysSecond / 3600) / 24);
                    var hour = Math.floor((sysSecond / 3600) % 24);
                    var minute = Math.floor((sysSecond / 60) % 60);
                    var second = Math.floor(sysSecond % 60);
                    $(dayElem).text(day); //计算天
                    $(hourElem).text(hour < 10 ? "0" + hour : hour); //计算小时
                    $(minuteElem).text(minute < 10 ? "0" + minute : minute); //计算分钟
                    $(secondElem).text(second < 10 ? "0" + second : second); //计算秒杀
                } else {
                    clearInterval(timer);
                }
            }, 1000);
        },
        /**
         * 类型(Y-m-d H:i:s)时间转换时间戳
         */
        toUnix: function (time) {
            var tmpDatetime = time.replace(/:/g, '-');
            tmpDatetime = tmpDatetime.replace(/ /g, '-');
            var arr = tmpDatetime.split("-");
            var now = new Date(Date.UTC(arr[0], arr[1] - 1, arr[2], arr[3] - 8, arr[4], arr[5]));
            return parseInt(now.getTime() / 1000);
        },
        toDatetime: function (time) {
            return new Date(parseInt(time) * 1000).toLocaleString().replace(/:\d{1,2}$/,' ');
        },
        toTime: function(times){
            var time = new Date(parseInt(times) * 1000);
            var y = time.getFullYear();
            var m = time.getMonth() + 1;
            m = m<10?"0"+m:m;
            var d = time.getDate();
            d = d < 10 ? '0' + d:d;
            var h = time.getHours();
            h = h < 10 ? '0' + h:h;
            var mi = time.getMinutes();
            mi = mi < 10 ? '0' + mi:mi;
            var s = time.getSeconds();
            s = s < 10 ? '0' + s:s;
            return y + '-' + m + '-' + d + ' ' + h +':'+ mi +':'+ s;
        },
        /**
         * 获取当前时间
         */
        getNowFormatDate: function () {
            var date = new Date();
            var seperator1 = "-";
            var seperator2 = ":";
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate + " " + date.getHours() + seperator2 + date.getMinutes() + seperator2 + date.getSeconds();
            return currentdate;
        },
        /**
         * 获取前天后天的日期(20170118，-1)
         */
        getDay: function (s,num){
            var y = parseInt(s.substr(0,4), 10);
            var m = parseInt(s.substr(4,2), 10)-1;
            var d = parseInt(s.substr(6,2), 10);
            var dt = new Date(y, m, d + num);
            y = dt.getFullYear();
            m = dt.getMonth()+1;
            d = dt.getDate();
            m = m<10?"0"+m:m;
            d = d<10?"0"+d:d;
            return y + "-" + m + "-" + d;
        },
        /**
         * 获取几天前或几天后的日期
         */
        getDateStr: function(AddDayCount) {
        var dd = new Date();
        dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
        var y = dd.getFullYear();
        var m = (dd.getMonth()+1)<10 ? ('0'+(dd.getMonth()+1)) : (dd.getMonth()+1);
        var d = dd.getDate() <10 ? ('0'+ dd.getDate()) :dd.getDate();
        return y+"-"+m+"-"+d;
        },
        /**
         * 通过值删除数组元素
         */
        deleteByValue: function (arr, valueToDelete) {
            var ret = $.grep(arr, function (value, i) {
                return value != valueToDelete;
            });
            return ret;
        },
        /**
         * 通过索引删除数组元素
         */
        deleteByIndex: function (arr, indexToDelete) {
            var reta = $.grep(arr, function (value, i) {
                return i != indexToDelete;
            });
            return reta;
        },
        /**
         * 判断字符串在数组的位置
         */
        arrIndexOf: function(arr, str){
        // 如果可以的话，调用原生方法
        if(arr && arr.length > 0){
            var len = arr.length;
            for(var i = 0; i < len; i++){
                var isString = JSON.stringify(arr[i]);
                // 定位该元素位置
                if(isString.indexOf(str) != -1){
                    return i;
                }
            }
        }
        // 数组中不存在该元素
        return -1;
        },
        /**
         * 获取地址参数
         */
        getUrlParams: function (url, name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = url.search.substr(1).match(reg);
            if (r !== null) return unescape(r[2]);
            return null;
        },
        /**
         * 从返回接口的数据是否含有错误
         * @param {object} data 待处理数据
         * @returns {boolean} true/false
         */
        hasError: function (data) {
            if ($.isPlainObject(data) && data.code) {
                var code = data.code;
                if (code !== "0") {
                    return false;
                }
            }
            return true;
        },
        /**
         * 需要域名时使用
         */
        domainName: function (data) {
            return '' + data;
        },
        /**
         * 获取内容
         */
        getCont: function (data) {
            return data.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&nbsp;/g, ' ').replace(/&amp;nbsp;/g, ' ');
        },
        /**
         * 四舍五入保留小数点
         */
        decimal: function (num,v)
    {
        var vv = Math.pow(10,v);
        return Math.round(num*vv)/vv;
    },
    /**
         * 清楚空格
         */
        clearSpace: function (data) {
            return data.replace(/\s/g,'');
        },
        /**
         * input光标放在最后
         */
        inputLast: function(obj){
            var len = obj[0].value.length;
            if (document.selection) {
                var sel = obj.createTextRange();
                sel.moveStart('character',len-1);
                sel.collapse();
                sel.select();
            } else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') {
                obj.selectionStart = obj.selectionEnd = len;
            }
        },
        /**
         * 判断输入内容是否是中文
         */
        isChinese: function(str){
            var entryVal=str;
            var cnChar=entryVal.match(/[^\x00-\x80]/g);
            if(cnChar!==null&&cnChar.length>0){
                return true;
            }else {
                return false;
            }
        },
        /**
         * 把数组分成多个数组
         */
        arrayChunk: function (array, size) {
            var result = [];
            for (var x = 0; x < Math.ceil(array.length / size); x++) {
                var start = x * size;
                var end = start + size;
                result.push(array.slice(start, end));
            }
            return result;
        },
        /**
         * 文本框只能输入数字
         */
        numOnly: function (selector) {
            $(selector).keyup(function () {
                this.value = this.value.replace(/[^\d]/g, '');
            });
        },
        /**
         * 转换小数数字
         */
        floatNum: function(oInput){
            if('' !== oInput.value.replace(/\d{1,}\.{0,1}\d{0,}/,''))
            {
                oInput.value = oInput.value.match(/\d{1,}\.{0,1}\d{0,}/) === null ? '' :oInput.value.match(/\d{1,}\.{0,1}\d{0,}/);
            }
        },
        /**
         * 文本框只能输入数字和小数点
         */
        numDotOnly: function (selector) {
            $(selector).keyup(function () {
                this.value = this.value.replace(/[^0-9.]/g, '');

            });
        },
        /**
         * 文本框只能输入数字和小数点后两位
         */
        numDotTwoOnly: function (selector) {
            $(selector).keyup(function () {
                this.value = this.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
                this.value = this.value.replace(/^\./g,""); //验证第一个字符是数字而不是
                this.value = this.value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的
                this.value = this.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
                this.value = thisc.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
            });
        },
        /**
         * 随机生成字符串
         */
        random: function (len) {
            len = len || 32;
            var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
            var maxPos = $chars.length;
            var rendomString = '';
            for (i = 0; i < len; i++) {
                rendomString += $chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return rendomString;
        },
        /**
         * 正则表达式验证
         */
        regex: {
            rgNotnull: /[\w\W]+/, // 不能为空！
            rgCharacterLimit: /^[\w\W]{6,16}$/, // 6到16位任意字符！
            rgNum: /^\d+$/, // 数字！
            rgNumLimit: /^\d{6,16}$/, // 6到16位数字！
            rgNoString: /^[\u4E00-\u9FA5\uf900-\ufa2d\w\.\s]+$/, // 特殊字符！
            rgStringLimit: /^[\u4E00-\u9FA5\uf900-\ufa2d\w\.\s]{6,18}$/, // 6到18位字符！
            rgPost: /^[0-9]{6}$/, // 请填写邮政编码！
            rgMobile: /^1[34578]\d{9}$/, // 手机号码！
            rgEmail: /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, // 邮箱地址格式!
            rgPhone: /^(\d{3,4}-)?\d{7,8}$/, // 电话或传真！
            rgUrl: /^(\w+:\/\/)?\w+(\.\w+)+.*$/ //网址
        },
        /**
         * 获取绝对路径，当页面需要进行跨模块调用时有用
         * @param {type} url
         * @returns {undefined}
         */
        getAbsoluteUrl: function (url) {
            return url;
        },
        /**
         * 获取认证信息
         * @returns {undefined}
         */
        getAuthInfo: function () {
            var _passport = this.getSession("_passport");
            var res = {
                // _app: "shop",
                // _platform: "web"
            };
            if (_passport) {
                res._passport = _passport;
            }
            return res;
        },
        /**
         * 设置认证信息
         * @param {object} data
         * @returns {undefined}
         */
        setAuthInfo: function (data) {
            var _passport = data && data._passport;
            this.setSession("_passport", _passport);
        },
        /**
         * 清楚认证信息
         * @returns {undefined}
         */
        clearAuthInfo: function () {
            this.delSession("_passport");
        },
        /**
         * 所有接口都有通用错误处理
         * @param {object} data
         * @returns {object}
         */
        catchCommonError: function (data) {
            if (!$.isPlainObject(data) || !data.error_code) { //错误数据格式
                return data;
            }
            var code = data.error_code,
                message = data.message;
            switch (code) {
                case "10000": //未登录
                    this._noLogin(data);
                    break;
                case "10001": //未登录
                    this._noLogin(data);
                    break;
            }
            return data;
        },
        /**
         * 解析url地址
         * @param {string} url 等待解析url地址
         * @return {object}
         */
        parseUrl: function (url) {
            var urlRegExp = new RegExp(/^([^:]+):\/\/(?:([^:@]+)(?::([^@]+))?@)?([^:\/]+)(?:\:([0-9]*))?([^#\?]+)?(?:\?([^#]+))?(#.+)?$/ig); // :RegExp
            var pathRegExp = new RegExp('([^/]+)', 'g'); // :RegExp
            var queryRegExp = new RegExp('([^=&]+)=([^&]+)', 'g'); // :RegExp
            var info = {
                url: url
            };
            var match = urlRegExp.exec(url);
            if (match !== null) {
                info.protocol = match[1] || ''; // 'https'
                info.user = match[2] || ''; // 'admin'
                info.password = match[3] || ''; // '123456'
                info.subdomain = match[4] || ''; // 'secure'
                info.domain = match[4] || ''; // 'example.com'
                info.port = match[5] || ''; // '8181'
                info.path = match[6] || ''; // '/local/test'
                info.query = match[7] || ''; // 'search=bk&show=page'
                info.hash = match[8] || ''; // '#content'
                var path = info.path.match(pathRegExp);
                info.parsePath = (path === null) ? [] : path;
                var parseQuery = {};
                info.query.replace(queryRegExp, function (match, c1, c2) {
                    parseQuery[c1] = c2;
                    return match;
                });
                info.parseQuery = parseQuery;
                return info;
            }
        },
        /**
         * 拼接url地址
         * @param {string} url url地址
         * @param {object} param url参数
         * @returns {string} 拼接后的url地址
         *
         */
        getUrl: function (url, param) {
            if (url.indexOf("?") !== -1) {
                url += "&" + $.param(param);
            } else {
                url += "?" + $.param(param);
            }
            return url;
        },
        /**
         * 返回当前url地址中的参数
         * @returns {object}
         */
        getUrlParam: function () {
            var urlInfo = this.parseUrl(window.location.href);
            return urlInfo && urlInfo.parseQuery;
        },
        /**
         * 获取会话中指定的值
         * @param {string} key 要获取的key
         * @return {stirng} 返回指定值
         */
        getSession: function (key) {
            if (sessionStorage) {
                return sessionStorage.getItem(key);
            } else {
                return $.cookie(key);
            }
        },
        /**
         * 设置会话指定值
         * @param {string} key 会话的key
         * @param {string} val 要设置的值
         * @returns {void}
         */
        setSession: function (key, val) {
            if (sessionStorage) {
                sessionStorage.setItem(key, val);
            } else {
                $.cookie(key, val, {
                    "path": "/"
                });
            }
        },
        /**
         *  删除指定会话值
         * @param {type} key
         * @returns {undefined}
         */
        delSession: function (key) {
            if (sessionStorage) {
                sessionStorage.removeItem(key);
            } else {
                $.removeCookie(key, {
                    "path": "/"
                });
            }
        },
        /**
         * 获取html文件url
         */
        getHtmlUrl: function (htmlFile) {
            return this.clientRoot + htmlFile;
        },
        /**
         * 默认图片
         */
        defaultImg: function(elm,src){
            $(elm).find('img').each(function(){
                var _this = this;
                var timer = setInterval(function() {
                    if (_this.complete) {
                        if(typeof _this.naturalWidth == "undefined" || _this.naturalWidth === 0){
                            _this.src = src;
                        }
                        clearInterval(timer);
                    }
                }, 300);
            });
        },
        removeImg: function(elm){
            $(elm).find('img').each(function(){
                var _this = this;
                var timer = setInterval(function() {
                    if (_this.complete) {
                        if(typeof _this.naturalWidth == "undefined" || _this.naturalWidth === 0){
                            _this.remove();
                        }
                        clearInterval(timer);
                    }
                }, 300);
            });
        },
        /**
         * 判断是否有passport
         */
        checkPassport: function(passport){
            var self = this;
            if(!passport){
                cloud.alert('未登录，请您先登录！',function(){
                    var returnLink = window.encodeURI(window.location.href);
                    self.setSession('returnLink', returnLink);
                    var link = Pub.getHtmlUrl('login.html');
                    window.location.href = link;
                });
            }
        },
        /**
         * 检查是否登录
         */
        checkLogin: function () {
            var _passport = this.getSession("_passport");
            if (_passport === null) {
                var link = this.getHtmlUrl('html/user/login.html');
                var returnLink = window.encodeURI(window.location.href);
                window.location.href = link;
                this.setSession('returnLink', returnLink);
            }
        },
        /**
         * 被迫下线，其他地方登录
         */
        loginOff: function(code,reason){
            var self = this;
            if(parseInt(code) === 10010){
                    cloud.asked('您的e买单账户于'+reason+'在其他地方登录，登录密码可能泄露，请及时修改！','重置密码','立即登录',function(){
                        var link = self.getHtmlUrl('login.html');
                        localStorage.clear('_passport');
                        window.location.href = link;
                    },function(){

                    });
            }
        },
        /**
         * 判断是否有交易密码
         */
        isPwd: function(){
            var self = this;
            var pwd = localStorage.getItem('_pay_pwd');
            if(parseInt(pwd) === 0){
                cloud.alert('未设置支付密码，请先设置',function(){
                    var payLink = window.encodeURI(window.location.href);
                    self.setSession('pay-link',payLink);
                    var link = self.getHtmlUrl('change-pay-password.html');
                    window.location.href = link;
                });
            }
        },
        /**
         * 未登录处理
         * @param {object} data 获取到的数据
         * @returns {void}
         */
        _noLogin: function (data) {
            var url = data.url;
            url += window.encodeURI(window.location.href);
            window.location.href = url;
        },
        /**
         * 设置登录相关的数据
         * @returns {undefined}
         */
        _setLoginData: function () {
            var href = window.location.href;
            var param = this.getUrlParam(href);
            if (param && param._passport) {
            }
        }


    };
    return Pub;
});
